package com.itheima.reggie.interceptor;

import com.alibaba.fastjson.JSON;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
@Component
public class LoginCheckInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取后端登录用户
        Long empId = (Long) request.getSession().getAttribute("employee");
        //Long empId = (Long) request.getSession().getAttribute("employee");
        if (empId != null){
            //有用户信息——不放行且响应给用户跳转登录页面
            BaseContext.setCurrentId(empId);
            return true;
        }
        //获取前端登录用户
        Long userId = (Long) request.getSession().getAttribute("user");


        if (userId != null){
            //有用户信息——不放行且响应给用户跳转登录页面
            BaseContext.setCurrentId(userId);
            return true;
        }

        response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
        //有放行
        return false;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
